;(function($, global) {
	var gameCode = function() {
		this.gameCodes = [];
		this.OPT_LEFT_TIME = 1000;
		this.RESULT_LEFT_TIME = 1 * 60;
		this.lastGameResult = {};
		this.currentGameResult = {};
	};

	gameCode.prototype.createGameCode = function(gameCode) {
		if (gameCode) {
			var code = {
				name: gameCode.name.value,
				content: gameCode.content.value,
				number: gameCode.number.value,
				money: gameCode.money.value,
				mutiplies: gameCode.mutiplies.value,
				mode: gameCode.mode.value,
				commission: ''
			}
			var tr = '<tr class="code" data-num="' + this.gameCodes.length + '">' + 
				'<td>' + code.name + '</td>' +
				'<td class="code-list">' + code.content + '</td>' +
				'<td>[' + code.number + '注]</td>' +
				'<td>' + code.money + '元</td>' +
				'<td>' + code.mutiplies + '倍</td>' +
				'<td>' + code.mode + '</td>' +
				'<td>' + code.commission + '</td>' +
				'<td><a href="javascript: void(0);" onclick="window.gameCode.deleteCode(this)" class="del icon-trash-empty">删除</a></td>' +
				'</tr>';
			$('#bets-cart tbody').append(tr);
			this.gameCodes.push(gameCode);
		}
	}

	gameCode.prototype.clearGameCode = function() {
		$('#bets-cart tr:gt(0)').remove();
		this.gameCodes.splice(0, this.gameCodes.length);
	}

	gameCode.prototype.addGameCode = function(gameCode) {
		this.gameCodes.push(gameCode || {});
	} 

	gameCode.prototype.deleteCode = function(_this) {
		var $tr = $(_this).parent().parent();
		var dataNum = +$tr.attr('data-num');
		this.gameCodes.splice(dataNum, 1);
		$tr.remove();
		global.gameCode.calculateResult();
	}

	gameCode.prototype.calculateResult = function() {
		var allCount = 0;
		var totalMoney = 0;
		var gameCodes = global.gameCode.gameCodes;
		if (gameCodes && gameCodes instanceof Array) {
			for (var index = 0; index < gameCodes.length; index++) {
				allCount += gameCodes[index].number.value;
				totalMoney += gameCodes[index].money.value;
			}
		}

		var count = 1;
		var money = 0;
		var unit = 0;
		var codes = [];
		$('#play-mod').children('b').each(function(index, element) {
			var indexOfOn = $(element).attr('class').split(' ').indexOf('on');
			if (indexOfOn >= 0) {
				unit = +$(element).attr('value');
				return;
			}
		});
		$('#num-select').children('div').each(function(index, element) {
			var oneLineCode = [];
			$(element).children('input').each(function(cursor, ele) {
				var indexOfChecked = $(ele).attr('class').split(' ').indexOf('checked');
				if (indexOfChecked >= 0) {
					oneLineCode.push($(ele).val());
				}
			});
			codes.push(oneLineCode);
		});
		for (var index = 0; index < codes.length; index++) {
			count *= codes[index].length;
		}
		money = count * unit;
		allCount += count;
		totalMoney += money;
		$('#all-count').text(allCount);
		$('#all-amount').text(totalMoney);
	}

	gameCode.prototype.showRandomCode = function() {
		return global.setInterval(generateRandomCode, 50);
	}

	function generateRandomCode() {
		var target = generateRandomNum();
		if (target.length === 5) {
			$('.num_right').children('em').each(function(index, element) {
			 	$(element).text(target[index]);
			});
		}
	}

	function generateRandomNum() {
		var source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
		var target = [];
		for (var index = 0; index < 5; index++) {
			target.push(source[Math.floor(Math.random() * 10)]);
		}
		return target;
	}

	gameCode.prototype.showLeftTime = function(time) {
		$('#kjsay').html('<em class="kjtips">正在开奖中...</em>').show();
		showTime(time);
	}

	function showTime(time) {
		if (time-- > 0) {
			var hour = getHour(time);
			var minute = getMinute(time);
			var second = getSecond(time);
			$('#timer_lottery > div.h').children('span').each(function(index, element) {
				$(element).text(hour.charAt(index));
			});
			$('#timer_lottery > div.m').children('span').each(function(index, element) {
				$(element).text(minute.charAt(index));
			});
			$('#timer_lottery > div.s').children('span').each(function(index, element) {
				$(element).text(second.charAt(index));
			});
			global.setTimeout(function() {showTime(time);}, 1000);
		} else {
			global.gameCode.setExpect();
			$('#kjsay').html('开奖倒计时(<em class="kjtips">' + global.gameCode.RESULT_LEFT_TIME + '</em>)').show();
			showLotteringResultTime(global.gameCode.RESULT_LEFT_TIME);
			global.interval = global.gameCode.showRandomCode();
			global.gameCode.showLeftTime(global.gameCode.OPT_LEFT_TIME);
		}
	}

	function showLotteringResultTime(time) {
		if (time-- > 0) {
			if (time % 10 === 0) {//每隔10s获取一次结果
				if (!$.isEmptyObject(global.gameCode.currentGameResult) ||
					(global.gameCode.lastGameResult.expect === global.gameCode.currentGameResult.expect &&
					global.gameCode.lastGameResult.openCode === global.gameCode.currentGameResult.openCode)) {
					getLotterResult();
				}
			}
			var minute = getMinute(time);
			var second = getSecond(time);
			$('#kjsay').html('开奖倒计时(<em class="kjtips">' + minute + ':' + second + '</em>)');
			global.setTimeout(function() {showLotteringResultTime(time);}, 1000);
		} else {
			$('#kjsay').html('<em class="kjtips">正在开奖中...</em>').show();
			if (global.gameCode.currentGameResult) {
				showLotterResult();
			} else {
				global.gameCode.getLotterResult();
			}
		}
	}

	function getLotterResult() {
		$.ajax({
			type: 'POST',
			url: '../../rest/main/cqssc/lastest',
			dataType: 'json',
			contentType: 'application/json;charset=UTF-8',
			data: {},
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					global.gameCode.currentGameResult.expect = response.expect;
					global.gameCode.currentGameResult.openCode = response.openCode;
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	}

	function showLotterResult() {
		global.gameCode.setExpect(+global.gameCode.currentGameResult.expect);
		global.gameCode.setLotterResult(global.gameCode.currentGameResult.openCode);
		global.gameCode.lastGameResult = global.gameCode.currentGameResult;
		global.gameCode.currentGameResult = {};
		global.gameCode.showLeftTime(global.gameCode.OPT_LEFT_TIME);
		if (global.interval) {
			global.clearInterval(global.interval);
		}
	}

	function getHour(time) {
		var hour = parseInt(time / 60 / 60 % 60);
		return hour < 10 ? ('0' + hour) : ('' + hour);
	}

	function getMinute(time) {
		var minute = parseInt(time / 60 % 60);
		return minute < 10 ? ('0' + minute) : ('' + minute);
	}

	function getSecond(time) {
		var second = parseInt(time % 60);
		return second < 10 ? ('0' + second) : ('' + second);
	}

	gameCode.prototype.setExpect = function(expect) {
		var contents = $('#lottery-current-text').text().split(' ');
		var expect = expect && +expect || ++contents[1];
		contents[1] = expect;
		$('#lottery-current-text').text(contents.join(' '));
		$('#last_action_no').text(++expect);
	}

	gameCode.prototype.setLotterResult = function(lotterResult) {
		if (lotterResult) {
			var results = lotterResult.split(',');
			if (!results || results.length !== 5) {
				window.alert('结果错误');
				return;
			} 
			$('.kj-hao').children('em').each(function(index, element) {
				$(element).text(results[index]);
			});
		}
	}

	gameCode.prototype.getLotterResultAndShow = function() {
		var _arguments = arguments;
		$.ajax({
			type: 'POST',
			url: '../../rest/main/cqssc/lastest',
			dataType: 'json',
			contentType: 'application/json;charset=UTF-8',
			data: {},
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					global.gameCode.lastGameResult.expect = response.expect;
					global.gameCode.lastGameResult.openCode = response.openCode;
					global.gameCode.setExpect(+global.gameCode.lastGameResult.expect);
					global.gameCode.setLotterResult(global.gameCode.lastGameResult.openCode);
					if (_arguments && _arguments.length === 2 && typeof _arguments[0] === 'function') {
						_arguments[0](_arguments[1]);
					}
					if (global.interval) {
						global.clearInterval(global.interval);
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	}

	gameCode.prototype.saveUserLotteryData = function(gameCodes) {
		if (!gameCodes || 0 === gameCodes.length) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您还未添加预投注</div',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		var paramArr = [];
		var param = {};
		for (var index = 0; index < gameCodes.length; index++) {
			var gameCode = gameCodes[index];
			param = {};
			param.lotteryPeriods = gameCode.expect.value;
			param.lotteryType = gameCode.lotteryType.value;
			param.lotteryPlay = gameCode.name.value;
			param.lotteryBettingCode = gameCode.content.value;
			param.lotteryBettingNumber = gameCode.number.value;
			param.lotteryBettingAmount = gameCode.money.value;
			param.lotteryBettingMode = gameCode.mode.key;
			param.lotteryBettingPrize = 0.1; //gameCode.name.value;
			param.lotteryBettingMultiple = gameCode.mutiplies.value;
			param.lotteryBettingStatus = 1;
			paramArr.push(param);
		}
		var source = {'lotteryList': paramArr};

		$.ajax({
			type: 'POST',
			url: '../../rest/lottery/saveLotteryBttingRecord',
			async: true,
			dataType: 'json',
			contentType : 'application/json;charset=UTF-8',
			data: JSON.stringify(source),
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					$('#num-select').find('input').each(function(index, element) {
						$(element).removeClass('checked').removeClass('on');
					});
					$('#bets-cart').find('tr.code').each(function(index, element) {
						$(element).remove();
					});
					$('#all-count').text(0);
					$('#all-amount').text(0);
					global.gameCode.gameCodes.splice(0, global.gameCode.gameCodes.length);
					global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">投注成功</div>',
											time: 3,
											okBtn: '确定'});

					$.ajax({
						type: 'POST',
						url: '../../rest/getTotalMoney',
						async: true,
						dataType: 'json',
						contentType: 'application/json; charset=UTF-8',
						data: JSON.stringify({}),
						success: function(response) {
							if (response && response.status === '00') {
								$("#yu-e").text(response.totalMoney);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							console.log(XMLHttpRequest);
							console.log(textStatus);
							console.log(errorThrown);
						},
						complete: function(XMLHttpRequest, textStatus) {
							console.log(XMLHttpRequest);
							console.log(textStatus);
						}
					});
				} else {
					global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">' + response.errorMsg + '</div>',
											time: 10,
											okBtn: '确定'});
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
				global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">网络错误</div>',
											time: 10,
											okBtn: '确定'});
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
			}
		});
	}

	gameCode.prototype.getOptLeftTime = function() {
		$.ajax({
			type: 'POST',
			url: '../../rest/main/getOptLeftTime',
			async: false,
			data: {gameType: encodeURIComponent($('.icon-list-alt').text() || '')},
			dataType: 'json',
			contentType: 'application/json; charset=UTF-8',
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					global.gameCode.OPT_LEFT_TIME = response.optLeftTime > 0 ? response.optLeftTime : 1000;
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
			}
		});
	}

	gameCode.prototype.getOpenLeftTime =  function() {
		$.ajax({
			type: 'POST',
			url: '../../rest/main/getOpenLeftTime',
			async: false,
			data: {gameType: encodeURIComponent($('.icon-list-alt').text() || '')},
			dataType: 'json',
			contentType: 'application/json; charset=UTF-8',
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					global.gameCode.RESULT_LEFT_TIME = response.openLeftTime > 0 ? response.openLeftTime : 1 * 60;
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
			}
		});
	}

	gameCode.prototype.createGeneralLotteryOrder = function() {
		var gameCodeCell = {};
		var gameCode = createCommonData();

		var codes = [];
		var length = $('#num-select').children('div').length;
		$('#num-select').children('div').each(function(index, element) {
			var oneLineCode = [];
			$(element).children('input').each(function(cursor, ele) {
				var indexOfChecked = $(ele).attr('class').split(' ').indexOf('checked');
				if (indexOfChecked >= 0) {
					gameCodeCell = {};
					gameCodeCell.key = $(ele).val();
					gameCodeCell.value = $(ele).val();
					oneLineCode.push(gameCodeCell);
					$(ele).removeClass('checked');
				}
			});
			oneLineCode.length && codes.push(oneLineCode);
		});
		
		if (codes.length === 0 || codes.length !== length) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">请至少选择<span class="btn btn-red">1</span>个数字</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		var num = 1;
		var content = '';
		for (var index = 0; index < codes.length; index++) {
			num *= codes[index].length;
			for (var cursor = 0; cursor < codes[index].length; cursor++) {
				if (cursor === codes[index].length - 1) {
					content += codes[index][cursor].value;
				} else {
					content += (codes[index][cursor].value + ' ');
				}
			}
			if (index < codes.length - 1) {
				content += ',';
			}
		}

		gameCodeCell = {};
		gameCodeCell.key = num;
		gameCodeCell.value = num;
		gameCode.number = gameCodeCell;

		gameCodeCell = {};
		gameCodeCell.key = content;
		gameCodeCell.value = content;
		gameCode.content = gameCodeCell;

		gameCodeCell = {};
		gameCodeCell.key = gameCode.money.key * num;
		gameCodeCell.value = gameCode.money.value * num;
		gameCode.money = gameCodeCell;

		global.gameCode.createGameCode(gameCode);
	}

	gameCode.prototype.createInputTypeLotteryOrder = function(dataId) {
		var content = $('#textarea-code').val().replace(/\s+/g, '');
		if (!content) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您选择或输入的数字错误</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		var gameCode = createCommonData();

		var flag = true;
		if (+dataId === 12) {
			flag = global.gameCode.createFiveStar(gameCode, content);
		} else if (+dataId === 22 || +dataId === 24) {
			flag = global.gameCode.createFourStar(gameCode, content);
		} else  if (+dataId === 32 || +dataId === 34 || +dataId === 36) {
			flag = global.gameCode.createThreeStar(gameCode, content);
		} else if (+dataId === 42 || +dataId === 44 || +dataId === 46) {
			flag = global.gameCode.createThreeStarCompose(gameCode, content);
		}

		if (flag) {
			global.gameCode.createGameCode(gameCode);
			$('#textarea-code').val('');
		}
	}

	function createCommonData() {
		var gameCodeCell = {};
		var gameCode = {};
		$('.play-list').children('a').each(function(index, element) {
			if ($(element).attr('class') === 'on') {
				gameCodeCell.key = $(element).attr('data-id');
				gameCodeCell.value = $(element).html();
				gameCode.name = gameCodeCell;
				return false;
			}
		});

		$('#play-mod').children('b').each(function(index, element) {
			var indexOfOn = $(element).attr('class').split(' ').indexOf('on');
			if (indexOfOn >= 0) {
				var modeValue = $(element).html();
				gameCodeCell = {};
				gameCodeCell.key = (modeValue === '元' ? 1 : modeValue === '角' ? 2 : 3);
				gameCodeCell.value = modeValue;
				gameCode.mode = gameCodeCell;

				gameCodeCell = {};
				gameCodeCell.key = $(element).attr('value');
				gameCodeCell.value = $(element).attr('value');
				gameCode.money = gameCodeCell;
				return false;
			}
		});

		var mutiplies = +$('#beishu-value').val() || 1;
		gameCodeCell = {};
		gameCodeCell.key = mutiplies;
		gameCodeCell.value = mutiplies;
		gameCode.mutiplies = gameCodeCell;

		var expect = $('#last_action_no').text();
		gameCodeCell = {};
		gameCodeCell.key = expect;
		gameCodeCell.value = expect;
		gameCode.expect = gameCodeCell;

		var lotteryType = $('div.icon-list-alt').text();
		gameCodeCell = {};
		gameCodeCell.key = lotteryType;
		gameCodeCell.value = lotteryType;
		gameCode.lotteryType = gameCodeCell;

		return gameCode;
	}

	gameCode.prototype.createFiveStar = function(gameCode, content) {
		if (content % 5 !== 0) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您选择或输入的数字错误</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		createInputTypeCommonData(gameCode, 5);
		return true;
	}

	gameCode.prototype.createFourStar = function(gameCode, content) {
		if (content % 4 !== 0) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您选择或输入的数字错误</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		createInputTypeCommonData(gameCode, 4);
		return true;
	}

	gameCode.prototype.createThreeStar = function(gameCode, content) {
		if (content % 3 !== 0) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您选择或输入的数字错误</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		createInputTypeCommonData(gameCode, 3);
		return true;
	}

	gameCode.prototype.createThreeStarCompose = function(gameCode, content) {
		if (content % 3 !== 0) {
			global.gameView.showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">您选择或输入的数字错误</div>',
										time: 10,
										okBtn: '确定'});
			return false;
		}
		createInputTypeCommonData(gameCode, 3);
		return true;
	}

	function createInputTypeCommonData(gameCode, type) {
		var content = $('#textarea-code').val().replace(/\s+/g, '');
		var length = content.length;
		var gameCodeCell = {};
		if (length % type !== 0) {
			$('#dialogue').show();
		} else {
			var num = length / type;
			gameCodeCell.key = num;
			gameCodeCell.value = num;
			gameCode.number = gameCodeCell;
			var text = '';
			for (var index = 0; index < length; index++) {
				if ((index + 1) !== length) {
					if ((index + 1) % type === 0) {
						text += (content.charAt(index) + '|');
					} else {
						text += (content.charAt(index) + ',');
					}
				} else {
					text += content.charAt(index);
				}
			}
			gameCodeCell = {};
			gameCodeCell.key = text;
			gameCodeCell.value = text;
			gameCode.content = gameCodeCell;
			gameCodeCell = {};
			gameCodeCell.key = gameCode.money.key * num;
			gameCodeCell.value = gameCode.money.value * num;
			gameCode.money = gameCodeCell;
		}
	}

	gameCode.prototype.cancelOrder = function(lotteryId) {
		var bettingInfo = {
			lotteryId: lotteryId
		}

		$.ajax({
			type: 'POST',
			url: '../../rest/lottery/cancelOrder',
			data: bettingInfo,
			dataType: 'json',
			// contentType: 'application/json; charset=UTF-8',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					window.alert('撤单成功');
				} else {
					window.alert('撤单失败');
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
				window.alert('系统错误');
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	}

	global.gameCode = new gameCode();
})(jQuery, window);